<template>
  <Transition name="slide-in-left">
    <div
      ref="editorContainerRef"
      class="mobile-editor"
      :style="{ height: windowHeight ? windowHeight + 'px' : '' }"
      v-if="visible"
    >
      <QuillEditor
        v-model:content="_modelValue"
        toolbar="full"
        theme="snow"
        content-type="html"
        :placeholder="placeholder"
        class="quill-editor flex-1"
        :class="[type]"
        ref="quillEditorRef"
        @update:content="editorChange"
      ></QuillEditor>
      <div class="buttons">
        <a-button @click="cancel">{{ $t("btnText.cancel") }}</a-button>
        <a-button type="primary" @click="ensure">{{
          $t("btnText.ensure")
        }}</a-button>
      </div>
    </div>
  </Transition>
</template>

<script setup lang="ts">
import { QuillEditor } from "@vueup/vue-quill";
import { nextTick, onMounted, ref, watch } from "vue";

type Props = {
  modelValue: string;
  placeholder?: string;
  visible?: boolean;
};
const _modelValue = ref();
const props = defineProps<Props>();
const emits = defineEmits(["update:modelValue", "update:visible"]);
const quillEditorRef = ref();

const windowHeight = ref("");
const editorContainerRef = ref<HTMLElement | undefined>();
const initEditor = () => {
  setTimeout(() => {
    nextTick(() => {
      if (!editorContainerRef.value) return;
      windowHeight.value = window.innerHeight + "px";
      let toolbar = editorContainerRef.value?.querySelector(
        ".ql-toolbar"
      ) as HTMLElement;
      let buttons = editorContainerRef.value?.querySelector(
        ".buttons"
      ) as HTMLElement;
      let ql_editor = editorContainerRef.value?.querySelector(
        ".ql-container"
      ) as HTMLElement;
      ql_editor.style.height =
        window.innerHeight - toolbar.offsetHeight - buttons.offsetHeight + "px";
    });
  });
};

const cancel = () => {
  emits("update:visible", false);
};

const ensure = () => {
  let realText = quillEditorRef.value.getText().trim();
  if (realText.length == 0) {
    emits("update:modelValue", "");
  } else {
    emits("update:modelValue", _modelValue.value);
  }
  emits("update:visible", false);
};
watch(
  () => props.visible,
  (visible) => {
    if (visible) {
      _modelValue.value = props.modelValue;
      initEditor();
    }
  }
);
</script>
<style></style>

<style lang="less">
.mobile-editor {
  height: 100vh;
  display: flex;
  flex-direction: column;
  position: fixed;
  inset: 0;
  z-index: 999999;
  background-color: #fff;
  .buttons {
    display: flex;
    gap: 82px;
    padding: 82px;
    & > * {
      flex: 1;
    }
  }
}
.quill-editor {
  text-transform: unset;
}

.slide-in-left-enter-active,
.slide-in-left-leave-active {
  transition: transform 0.5s;
}

.slide-in-left-enter-to,
.slide-in-left-leave-from {
  transform: translateX(0%);
}

.slide-in-left-enter-from,
.slide-in-left-leave-to {
  transform: translateX(100%);
}
</style>
